package com.demo.factory;

import com.demo.bean.MyBean;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.XPath;
import org.dom4j.io.SAXReader;

import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MyClassPathXmlApplicationContext implements MyFactory {


    private List<MyBean> beanList;
    //存对象，通过id获取
    private Map<String, Object> beanMap = new HashMap<>();

    public MyClassPathXmlApplicationContext(String fileName) {
        //解析配置文件读取每一行，存放在List
        //1.获取解析器
        SAXReader saxReader = new SAXReader();
        URL url = this.getClass().getClassLoader().getResource(fileName);
        try {
            //2.获取配置文件
            Document document = saxReader.read(url);
            //3.xpath解析
            XPath xPath = document.createXPath("beans/bean");
            List<Element> nodes = xPath.selectNodes(document);
            //遍历集合
            if (nodes != null && nodes.size() > 0) {
                beanList = new ArrayList<>();
                for (Element el : nodes) {
                    String id = el.attributeValue("id");
                    String calzz = el.attributeValue("class");
                    beanList.add(new MyBean(id, calzz));
                }
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        // --------------------------------------------
        //将id存上还有，类路径
        if (beanList != null && beanList.size() > 0) {
            for (MyBean myBean : beanList) {
                try {
                    Class<?> aClass = Class.forName(myBean.getClazz());
                    Object o = aClass.newInstance();
                    beanMap.put(myBean.getId(), o);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

    }

    @Override
    public Object myGetBean(String name) {
        return beanMap.get(name);
    }
}
